import { listAccountOrganization, pageAccount, updateAccount } from "../../../service/api/api-admin-account"
import Message from 'tdesign-miniprogram/message/index';
import { debounce } from "../../../miniprogram_npm/tdesign-miniprogram/common/utils";
// pages/admin/account/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    accountList: [],
    accountListSearch: [],
    viewDrawerVisible: false,
    accountData: {},
    saveAccountOrganizations: [],//当前账号的组织
    isActivation: 0,//用户激活状态
    state: 0,//用户状态
    value: '',//搜索框内容
    //分页
    currentPage: 1, // 当前页数
    pageSize: 10, // 每页数据数量
    hasMoreData: true, // 是否还有更多数据
    total: 0,//所有数据条数
    firstReachBottom: 0,//是否第一次触底
  },
  onSearchSelectedClear(e) {
    this.loadAccountList({ current: this.data.currentPage, pageSize: this.data.pageSize })
    this.setData({
      currentPage: 1,
      hasMoreData: true
    })
  },
  //防抖搜索
  handleSearch(value) {

    if (value == "") { // 输入框的值为空时，显示全部数据
      this.setData({
        currentPage: 1,
        hasMoreData: true
      })
      this.loadAccountList({ current: 1, pageSize: this.data.pageSize })
    } else {
      const accountList = this.data.accountListSearch.filter(item => {
        let name = item.name ? item.name : ''
        let phone = item.phone ? item.phone : ''
        if (name.includes(value) || phone.includes(value)) {
          item.show = true
          return true;
        } else {
          // item.show = false
          return false;
        }
      })
      this.setData({
        accountList: accountList,
        hasMoreData: false
      })
    }
  },
  //搜索
  changeHandle(e) {
    const { value } = e.detail;
    debounce(this.handleSearch(value), 1000)
  },
  //加载当前编辑的用户的组织信息
  async loadListAccountOrganizationData() {
    const response = await listAccountOrganization({ accountId: this.data.accountData.id });
    if (response.code === 0) {
      const values = response.data.map((item) => {
        return {
          id: item.id,
          organizations: item.organizationCascaders.map((item) => ({
            organizationId: item.id,
            organizationName: item.name,
          })),
          organizationCascaderIds: item.organizationCascaders.map((item) => item.id),
          roles: item.roles.map((item) => ({
            roleId: item.id,
            roleName: item.name,
          })),
        };
      });
      this.setData({
        saveAccountOrganizations: values
      })
    }
  },
  //修改激活状态
  async onActiveChange(e) {
    const value = this.data.saveAccountOrganizations.map((item) => {
      const organization = item.organizations[item.organizations.length - 1];
      return {
        organizationId: organization.organizationId,
        organizationCascaderIds: item.organizations.map((item) => item.organizationId),
        organizationCascaderNames: item.organizations.map((item) => item.organizationName),
        roleIds: item.roles.map((item) => item.roleId),
      };
    });
    const response = await updateAccount({
      id: this.data.accountData.id,
      isActivation: e.detail.value,
      organizations: value,
    });
    this.setData({
      isActivation: e.detail.value
    })
    if (response.code === 0) {
      Message.success({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '修改成功',
        closeBtn: true,
      });
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '修改失败',
        closeBtn: true,
      });
    }
  },
  //关闭抽屉
  onCloseDrawer() {
    this.data.accountList.map((item, index) => {
      if (item.id === this.data.accountData.id) {
        this.data.accountList[index].state = Number(this.data.state)
        this.data.accountList[index].isDeleted = Number(this.data.isActivation)
        console.log(this.data.accountList[index]);
        this.setData({
          accountList: this.data.accountList
        })
      }
    })
  },
  //修改状态
  async onStateChange(e) {
    const value = this.data.saveAccountOrganizations.map((item) => {
      const organization = item.organizations[item.organizations.length - 1];
      return {
        organizationId: organization.organizationId,
        organizationCascaderIds: item.organizations.map((item) => item.organizationId),
        organizationCascaderNames: item.organizations.map((item) => item.organizationName),
        roleIds: item.roles.map((item) => item.roleId),
      };
    });
    const response = await updateAccount({
      id: this.data.accountData.id,
      state: e.detail.value,
      organizations: value,
    });
    this.setData({
      state: e.detail.value
    })
    if (response.code === 0) {
      Message.success({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '修改成功',
        closeBtn: true,
      });
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '修改失败',
        closeBtn: true,
      });
    }
  },
  //点击编辑
  onClickEdit(e) {
    let item = e.currentTarget.dataset.item
    this.setData({
      isActivation: item.isActivation,
      state: item.state,
      accountData: item
    })
    this.loadListAccountOrganizationData()
  },
  async loadAccountList(params: { current: number, pageSize: number }) {
    wx.showLoading({
      title: '加载中...'
    })
    const response = await pageAccount({ current: params.current, pageSize: params.pageSize });
    const responseSearch = await pageAccount({ current: 1, pageSize: 100000 });
    const list = response.data.data.map((item) => ({ ...item, show: true }))
    const listSearch = responseSearch.data.data.map((item) => ({ ...item, show: true }))
    console.log(response);
    if (response.code === 0) {
      wx.hideLoading()
      this.setData({
        accountList: list,
        total: response.data.total,
        accountListSearch: listSearch,

      })
    }
  },
  /**
* 页面相关事件处理函数--监听用户下拉动作
*/
  onPullDownRefresh: function () {
    this.onRefresh();
  },
  async onRefresh() {
    this.setData({
      value: ''
    })
    //导航条加载动画
    wx.showNavigationBarLoading();
    //停止下拉刷新
    const response = await pageAccount({ current: 1, pageSize: 8, });
    if (response.code === 0) {
      const hasMoreData = response.data.total > 8;
      const list = response.data.data.map((item) => ({ ...item, show: true }))
      this.setData({
        accountList: list,
        hasMoreData,
        currentPage: 1,
        pageSize: 8,
        total: response.data.total,
      })
      setTimeout(() => {
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }, 1000);
    }
  },
  // 下拉加载更多数据
  onReachBottom() {
    this.setData({
      firstReachBottom: this.data.firstReachBottom + 1
    })
    if (this.data.total > this.data.pageSize) {
      wx.showLoading({
        title: '加载中...'
      })
      if (this.data.hasMoreData) {
        const nextPage = this.data.currentPage + 1;
        this.setData({
          currentPage: nextPage
        })
        this.getAccountListPage({ current: nextPage, pageSize: this.data.pageSize })
        wx.hideLoading()
      } else {
        if (this.data.firstReachBottom === this.data.currentPage) {
          wx.showToast({
            title: '已加载完成'
          })
        }
        wx.hideLoading()
      }
    }
  },
  //获取选题列表用于下拉加载更多
  async getAccountListPage(params: { current: number, pageSize: number }) {
    wx.showLoading({
      title: '加载中...'
    })
    try {
      const response = await pageAccount({ current: params.current, pageSize: params.pageSize });
      const hasMoreData = response.data.total >= params.pageSize * params.current;
      const list = response.data.data.map((item) => ({ ...item, show: true }))
      this.setData({
        accountList: [...this.data.accountList, ...list],
        total: response.data.total,
        hasMoreData
      })
      wx.hideLoading()
    } catch (error) {
      wx.hideLoading()
    }
  },
  //打开编辑抽屉
  openEditDrawer() {
    this.setData({
      viewDrawerVisible: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const { globalData: { currentUser, navBarHeight, access } } = getApp();
    this.setData({
      currentUser,
      navBarHeight,
      access
    })
    this.loadAccountList({ current: this.data.currentPage, pageSize: this.data.pageSize })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})